package com.auto.ftl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.auto.entity.User;

import freemarker.core.Environment;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMarkerHandler extends HttpServlet{
	private Configuration configuration = null; //解释Configuration
	
	//构造函数
	public FreeMarkerHandler(){
		configuration = new Configuration();
		//输出的数据默认的编码类型
		configuration.setDefaultEncoding("utf-8");
		/*//方法a：处理空值
		configuration.setClassicCompatible(true);*/
		
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("title", "FreeMarker空值测试");
		List<User> userList = new ArrayList<User>();
		
		//注值到对象中
		User user1 = new User();
		user1.setId(1);
		user1.setName("小明");
		User user2 = new User();
		user2.setId(2);
		user2.setName(null);//这里注空值，前台测试用的
		userList.add(user1);
		userList.add(user2);
		dataMap.put("userList", userList); //将数据放到Map中
		configuration.setServletContextForTemplateLoading(getServletContext(),"WEB-INF/template");
		
		/*//方法e:空值处理
		//加载并设置freemarker.properties  
        Properties p = new Properties();  
        p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("freemarker.properties"));  
        try {
			configuration.setSettings(p);
		} catch (TemplateException e1) {
			e1.printStackTrace();
		}  
		*/
		//获得需要装载的模版
		Template template = null;
		try {
			template = configuration.getTemplate("test.ftl");
			template.setEncoding("utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//生成输出
        response.setContentType("text/html; charset=" + template.getEncoding());
        PrintWriter out = response.getWriter();
        
        
        //合并数据模型和模版，并将结果输出到out中
        try
        {
        	/*//方法b：处理空值
        	Environment env = template.createProcessingEnvironment(dataMap, out);
    		env.setClassicCompatible(true);
    		env.process();*/
        	template.process(dataMap,out);//和上面的process()方法选一种
        }
        catch(TemplateException e)
        {
        	throw new ServletException("处理Template模版中出现错误", e);
        }
	}
	
}
